<template>
	<view class="router-view bcl-active">
		<!-- 聊天列表 -->
		<scroll-view class="scroll-view" scroll-y :show-scrollbar="true" :scroll-top="scrollTop" @scrolltoupper="onScrollToUpper"
		 :scroll-with-animation="true">
			<view class="chat-list container">
				<view class="item box mb-30" :class="{ self: item.flow == 'out' }" v-for="(item, index) in chats" :key="index">
					<!-- 头像 -->
					<view @click="jumpToUserDetail(item)" class="uni-avatar uni-avatar-lg mr-10">
						<image :src="myAvatar || defaultImage" v-if="item.flow == 'out'" />
						<image :src="userAvatar || defaultImage" v-else />
					</view>

					<!-- 信息 -->
					<view class="info box-1">
						<!-- 时间 -->
						<view class="date cl-second">{{
              moment(item && item.time * 1000)
                .locale("zh-cn")
                .calendar()
            }}</view>

						<!-- 消息 -->
						<view class="message-box mt-10">
							<!-- 文字类型 -->
							<view class="message container border border-deep radius bcl-white" v-if="item && item.type == 'TIMTextElem'">
								<text :class="{
                    'cl-primary underline':
                      item &&
                      item.payload.text &&
                      /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/.test(
                        item.payload.text
                      ),
                  }">{{ item && item.payload.text }}</text>
							</view>

							<!-- 图片类型 -->
							<view class="message container border border-deep radius bcl-white" v-else>
								<image class="block" :src="item && item.payload.imageInfoArray[0].imageUrl" mode="widthFix" @tap="
                    previewImage(
                      item && item.payload.imageInfoArray[0].imageUrl
                    )
                  " />
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 操作栏 -->
		<view class="operation box box-column-center bcl-white border border-bottom pl-15" :class="{ focused: focused }">
			<view class="uni-input box-1 bcl-white">
				<input v-model="words" type="text" placeholder="说点什么~" confirm-type="send" :confirm-hold="true" @confirm="createMessage(1)"
				 @focus="onFocus" @blur="onBlur" />
			</view>

			<view class="image-btn box box-center pointer pointer-bcl" @tap="chooseImage">
				<image src="/static/images/icon_image.png" />
			</view>
			<view class="send-btn box box-center pointer pointer-bcl" @tap="createMessage(1)">
				<image src="/static/images/icon_send.png" />
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from "vuex";
	import initTim from "@/utils/initTim";
	// #ifdef H5
	import TIM from 'tim-js-sdk';
	// #endif
	// #ifndef H5
	import TIM from 'tim-wx-sdk';
	// #endif
	import moment from "moment";

	export default {

		data() {
			return {
				words: "", // 输入框内容
				chats: [], // 聊天列表
				toUserId: "", // 接收方用户ID
				conversationId: "", // 会话ID
				nextReqMessageId: "", // 用于续拉，分页续拉时需传入该字段
				myAvatar: "",
				userAvatar: "",
				defaultImage: this.$config.default,
				scrollTop: 0,
				focused: false,
				sending: false,
			};
		},
		onLoad(options) {
			let {
				toUserId = "", conversationId = ""
			} = options;
			if (conversationId) {
				this.conversationId = conversationId;
				this.toUserId = conversationId.substring(3);
			} else if (toUserId) {
				this.toUserId = toUserId;
				this.conversationId = `C2C${this.toUserId}`;
			}
			console.log("43434", this.toUserId)
			// 初始化腾讯IM
			if (this.tim) {
				this.getMessageList();
				this.getMyProfile();
				this.getUserProfile();
			} else {
				this.initTim();
			}
		},
		methods: {
			jumpToUserDetail(user) {
				uni.navigateTo({
					url: `/user/info/userTaskList?uid=${this.toUserId}&nick=${user.nick}&avatar=${user.avatar}`
				})
			},
			/*
			 * 初始化腾讯IM
			 */
			async initTim() {
				let tim = await initTim();
				this.SET_TIM(tim);
				this.getMessageList();
				this.getMyProfile();
				this.getUserProfile();
			},
			/*
			 * 获取消息列表
			 */
			getMessageList(histroy = false) {
				if (!this.tim) return false;
				// 持续监听消息
				!histroy &&
					this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
						console.log("接受到消息：", event.data);
						// 插入消息
						this.chats.push(...event.data);
						this.scrollToBottom();
					});
				uni.showLoading({
					mask: true,
				});
				// 获取消息列表
				this.tim
					.getMessageList({
						conversationID: this.conversationId,
						nextReqMessageID: this.nextReqMessageId,
						count: 10,
					})
					.then((res) => {
						uni.hideLoading();
						console.log("获取消息列表成功：", res);
						// 插入信息
						this.chats[histroy ? "unshift" : "push"](...res.data.messageList);
						this.nextReqMessageId = res.data.nextReqMessageID;
						if (histroy && res.data.messageList.length == 0) {
							this.$toast("无更多消息");
						} else if (!histroy) {
							this.scrollToBottom();
						}
						console.log("已读上报");
						// 已读上报
						this.tim.setMessageRead({
							conversationID: this.conversationId
						});
					})
					.catch((err) => {
						uni.hideLoading();
						console.error("获取消息列表失败: ", err);
						this.$toast("获取消息列表失败");
					});
			},
			/*
			 * 创建消息
			 */
			createMessage(type = 1, file) {
				if (type == 1 && this.words == "") {
					this.$toast("消息不能为空");
					return false;
				}
				try {
					if (this.sending) return false;
					uni.showLoading({
						mask: true,
					});
					let message = null;
					// 创建文本消息
					if (type == 1) {
						message = this.tim.createTextMessage({
							to: this.toUserId,
							conversationType: TIM.TYPES.CONV_C2C,
							payload: {
								text: this.words,
							},
						});
					} else if (type == 2) {
						let payload = null;
						// #ifdef H5
							payload  = file;
						// #endif
						// #ifndef H5
							payload = file; 
						// #endif
						
						console.log("dada ----- ",payload);
						message = this.tim.createImageMessage({
							to: this.toUserId,
							conversationType: TIM.TYPES.CONV_C2C,
							payload: {
								"file": payload
							}
						});

						// message = this.tim.createImageMessage({
						//   to: this.toUserId,
						//   conversationType: TIM.TYPES.CONV_C2C,
						//   payload: {
						//     file:file.tempFiles[0],
						//   },
						// });
					}
					console.log("msg ----- ",message);
					this.sendMessage(message);
				} catch (err) {
					this.sending = false;
					console.error("创建消息失败: ", err);
					this.$toast("创建消息失败");
				}
			},
			/*
			 * 发送消息
			 */
			sendMessage(message) {
				this.sending = true;
				this.tim
					.sendMessage(message)
					.then((res) => {
						this.sending = false;
						uni.hideLoading();
						this.words = "";
						console.log("发送成功: ", res);
						// 插入信息
						this.chats.push(res.data.message);
						this.scrollToBottom();
					})
					.catch((err) => {
						this.sending = false;
						uni.hideLoading();
						console.error("发送消息失败: ", err);
						this.$toast("发送消息失败");
					});
			},
			/*
			 * 上传图片
			 */
			chooseImage() {
				let _this = this;
				uni.chooseImage().then((chunk) => {
					let [err, res] = chunk;
					if (res) {
						setTimeout(() => {
							_this.createMessage(2, res);
						}, 1000);
					} else {
						console.err("选择失败: ", err);
						this.$toast("选择失败");
					}
				});
			},
			/*
			 * 预览图片
			 */
			previewImage(url) {
				uni.previewImage({
					current: url,
					urls: [url],
				});
			},
			/**
			 * 获取我的资料
			 */
			getMyProfile() {
				this.tim.getMyProfile().then((res) => {
					console.log("获取我的资料", res);
					this.myAvatar = res.data.avatar;
				});
			},
			/**
			 * 获取对方资料
			 */
			getUserProfile() {
				console.log("121", this.toUserId)
				this.tim
					.getUserProfile({
						userIDList: [this.toUserId],
					})
					.then((res) => {
						console.log("获取对方资料", res);
						this.userAvatar = res.data[0].avatar;
						this.userNickName = res.data[0].nick;
						uni.setNavigationBarTitle({
							title: this.userNickName ? `与${this.userNickName}的对话` : "聊天",
						});
					});
			},
			/*
			 * 滚动到底部
			 */
			scrollToBottom() {
				this.$nextTick(() => {
					this.scrollTop = 10000000 * Math.random();
				});
			},
			/*
			 * 触顶
			 */
			onScrollToUpper() {
				this.getMessageList(true);
			},
			onFocus() {
				// #ifndef H5
				this.focused = true;
				// #endif
			},
			onBlur() {
				this.focused = false;
			},
			moment,
			...mapActions(["SET_TIM"]),
		},
		computed: {
			...mapState(["userInfo", "tim"]),
		},
	};
</script>

<style lang="scss" scoped>
	.router-view {
		height: 100%;
		overflow: hidden;

		// 操作栏
		.operation {
			height: 100upx;

			&.focused {
				transform: translateY(-15px);
			}

			.uni-input {
				margin-bottom: 0;
				border-radius: 200upx;
				padding: 15upx 20upx;
			}

			// 按钮
			.image-btn,
			.send-btn {
				width: 100upx;
				height: 100%;

				// background: url("/static/images/icon_image.png") no-repeat center / 50upx;
				image {
					display: block;
					width: 50upx;
					height: 50upx;
				}
			}
		}

		// 聊天列表
		.scroll-view {
			height: calc(100% - 100upx);

			.chat-list {
				.item {
					.info {
						.message-box {
							margin-right: 20%;

							.message {
								display: inline-block;

								image {
									width: 200upx;
								}
							}
						}
					}

					// 自己
					&.self {
						flex-direction: row-reverse;

						.uni-avatar {
							margin: 0;
							margin-left: 20upx;
						}

						.info {
							.date {
								text-align: right;
							}

							.message-box {
								display: flex;
								justify-content: flex-end;
								margin-left: 20%;
								margin-right: 0;
							}
						}
					}
				}
			}
		}
	}
</style>
